package projeto.comercial.gerenciarservico.cgd;

import java.util.Collection;
import java.util.List;

import javax.persistence.Query;

import org.springframework.stereotype.Repository;

import plataforma.base.cdp.Criterio;
import plataforma.base.cdp.ObjetoPagina;
import plataforma.crudestatico.cgd.DaoBase;
import projeto.comercial.cliente.cdp.Cliente;
import projeto.comercial.gerenciarservico.cdp.Servico;
import projeto.comercial.oportunidade.cdp.OportunidadeServico;

@Repository
public class DaoGerenciarServicos extends DaoBase<Servico>{
	@Override
	public Servico recuperarPorId(Long id) {
		String hql = "select distinct s from Servico s "
				+ " left outer join fetch s.cliente "
				+ " left outer join fetch s.kservico "
				+ " left outer join fetch s.informacoes " 
				+ " where s.id=:parId ";


		Query query = getEntityManager().createQuery(hql);
		query.setParameter("parId", id);

		return (Servico) query.getSingleResult();
	}
	
	
	public Collection<Servico> recuperarTodosPaginado(ObjetoPagina objetoPagina) {
		
		StringBuilder sb = new StringBuilder();
		sb.append("select s from Servico s left outer join fetch s.cliente ");

		// adicionando where
		sb.append(" where 1=1 ");

		if (objetoPagina.getCriteriosSimples() != null) {

			for (Criterio criterio : objetoPagina.getCriteriosSimples()) {

				sb.append(" and " + criterio.toHQL());

			}

		}
		if (objetoPagina.getCriterioOrdenacao() != null)
			sb.append(" order by "
					+ objetoPagina.getCriterioOrdenacao().toString());

		Query consulta = getEntityManager().createQuery(sb.toString());
		consulta.setFirstResult(objetoPagina.getFirstResults());
		consulta.setMaxResults(objetoPagina.getMaxResults());

		return (Collection<Servico>) consulta.getResultList();

	}
	
	
	@Override
	public int recuperarQteTodos(ObjetoPagina objetoPagina) {
				
		StringBuilder sb = new StringBuilder();
		sb.append(" select count(id) from Servico s");
		// adicionando where
		sb.append(" where 1=1 ");

		if (objetoPagina.getCriteriosSimples() != null) {

			for (Criterio criterio : objetoPagina.getCriteriosSimples()) {

				sb.append(" and " + criterio.toHQL());

			}

		}

		Long count = (Long) getEntityManager().createQuery(sb.toString())
				.getSingleResult();

		return count.intValue();
	}



}
